
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="API名称" prop="apiName">
        <el-input
          v-model="queryParams.apiName"
          placeholder="请输入API名称"
          clearable
          size="small"
          style="width:150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="API编码" prop="apiCode">
        <el-input
          v-model="queryParams.apiCode"
          placeholder="请输入API编码"
          clearable
          size="small"
          style="width:150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请求方式" prop="requestType">
        <el-select v-model="queryParams.requestType" placeholder="请选择请求方式" clearable size="small" style="width:150px">
          <el-option
            v-for="dict in requestTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属应用" prop="appName">
        <el-select v-model="queryParams.appName" placeholder="请选择所属应用" clearable size="small" style="width:150px">
          <el-option
            v-for="dict in appTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据级别" prop="dataLevel">
        <el-select v-model="queryParams.dataLevel" placeholder="请选择数据级别" clearable size="small" style="width:150px">
          <el-option
            v-for="dict in dataLevelOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['integration:apiServiceConfig:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['integration:apiServiceConfig:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['integration:apiServiceConfig:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="multiple"
          @click="useStatus(true)"
          v-hasPermi="['integration:apiServiceConfig:update']"
        >启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-video-pause"
          size="mini"
          :disabled="multiple"
          @click="useStatus(false)"
          v-hasPermi="['integration:apiServiceConfig:update']"
        >禁用
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border ref="fileTable" v-loading="loading" :data="apiServiceConfigList" @selection-change="handleSelectionChange" :row-class-name="tabRowClassName" @row-click="selectThisRow" >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="API名称" align="center" prop="apiName"/>
      <el-table-column label="API编码" align="center" prop="apiCode" show-overflow-tooltip />
      <el-table-column label="请求方式" align="center" prop="requestType" :formatter="requestTypeFormat"/>
      <el-table-column label="所属应用" align="center" prop="appName" :formatter="appNameFormat"/>
      <el-table-column label="内容格式" align="center" prop="dataType" show-overflow-tooltip/>
      <el-table-column label="数据级别" align="center" prop="dataLevel" :formatter="dataLevelFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleApiTest(scope.row)"
            v-hasPermi="['integration:apiServiceConfig:test']"
          >测试
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['integration:apiServiceConfig:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['integration:apiServiceConfig:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleOpenTemplate(scope.row)"
            v-hasPermi="['integration:apiServiceConfig:edit']"
          >模板配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 测试APi服务对话框 -->
    <el-dialog :title="title" :visible.sync="openTest" width="60%" height="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-form-item label="APIId" prop="apiName" v-if="false">
            <el-input v-model="form.id" placeholder="请输入APIId"/>
          </el-form-item>
          <el-form-item label="API名称" prop="apiName">
            <el-input v-model="form.apiName" placeholder="请输入API名称"/>
          </el-form-item>
          <el-form-item label="请求参数" prop="paramTemplate">
            <el-input v-model="form.paramTemplate" type="textarea" rows="5" placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item label="响应结果" prop="paramResult">
            {{responseResult}}
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="test">测试</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改API服务配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="API名称" prop="apiName">
              <el-input v-model="form.apiName" placeholder="请输入API名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="API编码" prop="apiCode">
              <el-input v-model="form.apiCode" placeholder="请输入API编码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="API地址" prop="apiUrl">
              <el-input v-model="form.apiUrl" placeholder="请输入API地址"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属应用" prop="appName">
              <el-select v-model="form.appName" placeholder="请选择所属应用">
                <el-option
                  v-for="dict in appTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="请求方式" prop="requestType">
              <el-select v-model="form.requestType" placeholder="请选择请求方式">
                <el-option
                  v-for="dict in requestTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容格式" prop="dataType">
              <el-select v-model="form.dataType" placeholder="请输入内容格式" >
                <el-option
                  v-for="dict in contentTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="数据级别" prop="dataLevel" v-if="condition">
          <el-select v-model="form.dataLevel" placeholder="请选择数据级别">
            <el-option
              v-for="dict in dataLevelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打开配置模板修改页面 -->
    <el-dialog :title="title" :visible.sync="openTemplate" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="参数模板" prop="paramTemplate">
          <el-input v-model="form.paramTemplate" type="textarea"
                    :autosize="{ minRows: 10, maxRows: 35}"
                    placeholder="请输入内容" style="width: 90%"/>
        </el-form-item>
        <el-dialog
          width="80%"
          title="修改子模板"
          :visible.sync="openChildTemplates"
          append-to-body>
          <el-form-item label="子参数模板" prop="subParamTemplate">
            <el-input v-model="form.subParamTemplate" type="textarea"
                      :autosize="{ minRows: 10, maxRows: 35}"
                      placeholder="请输入内容" style="width: 90%"/>
          </el-form-item>
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="type" v-if="this.form.appName === 'jingsui'" @click="openChildTemplates = true">打 开 子 模 板</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listApiServiceConfig,
    getApiServiceConfig,
    delApiServiceConfig,
    addApiServiceConfig,
    updateApiServiceConfig,
    testApi,
    useById
  } from "@/api/integration/apiServiceConfig";
  import {getTables} from "@/api/datafactory/table";
  import {updateStatus} from "@/api/datafactory/work";

  export default {
    name: "ApiServiceConfig",
    components: {},
    data() {
      return {
        //数据状态
        status:false,
        // 隐藏数据级别
        condition:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // API服务配置表格数据
        apiServiceConfigList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openTest: false,
        openTemplate: false,
        openChildTemplates : false,
        // 响应结果
        responseResult: "",
        // 请求方式字典
        requestTypeOptions: [],
        // 数据级别字典
        dataLevelOptions: [],
        // 业务对象列表
        apiObjOptions: [],
        //所属应用列表
        appTypeOptions: [],
        //内容格式列表
        contentTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          apiName: null,
          requestType: null,
          appName: null,
          createName: null,
          dataLevel: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          requestType: [
            {required: true, message: "请求方式不能为空", trigger: "change"}
          ],
          apiUrl: [
            {required: true, message: "API地址不能为空", trigger: "blur"}
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("request_type").then(response => {
        this.requestTypeOptions = response.data;
      });
      this.getDicts("data_level").then(response => {
        this.dataLevelOptions = response.data;
      });
      this.getDicts("app_type").then(response => {
        this.appTypeOptions = response.data;
      });
      this.getDicts("data_type").then(response => {
        this.contentTypeOptions = response.data;
      });
      var query = {};
      getTables(query).then(response => {
        this.apiObjOptions = response.data;
      });

    },
    methods: {
      /** 更改斑马纹 */
      tabRowClassName({row,rowIndex}){
        let index = rowIndex + 1;
        if(index %2 == 0){
          return 'two-color'
        }else {
          return "one-color"
        }
      },
      /** 查询API服务配置列表 */
      getList() {
        this.loading = true;
        listApiServiceConfig(this.queryParams).then(response => {
          this.apiServiceConfigList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 请求方式字典翻译
      requestTypeFormat(row, column) {
        return this.selectDictLabel(this.requestTypeOptions, row.requestType);
      },
      // 数据级别字典翻译
      dataLevelFormat(row, column) {
        return this.selectDictLabel(this.dataLevelOptions, row.dataLevel);
      },
      apiObjFormat(row, column) {
        return this.selectDictLabel(this.dataLevelOptions, row.dataLevel);
      },
      appNameFormat(row,column){
        return this.selectDictLabel(this.appTypeOptions,row.appName)
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.openTest = false;
        this.openTemplate = false;
        this.openChildTemplates = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          apiName: null,
          apiCode: null,
          requestType: null,
          apiObj: null,
          appName: null,
          apiUrl: null,
          dataType: null,
          paramTemplate: null,
          paramResult: null,
          createId: null,
          createName: null,
          createTime: null,
          dataLevel: null,
          orderNo: null
        };
        this.responseResult = "";
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      selectThisRow(row) {
          this.$refs.fileTable.toggleRowSelection(row);
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加API服务配置";
        this.condition=false;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.condition=true;
        const id = row.id || this.ids
        getApiServiceConfig(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改API服务配置";
        });
      },
      useStatus(status){
        this.status = status;
        let statusNo = 0;
        if (status === true) {
          var dataStatus = '启动';
          statusNo = 1;
        } else {
          dataStatus = '禁用';
          statusNo = 2;
        }
        const id = this.ids;
        this.$confirm('是否' + dataStatus + '"' + id + '"的数据项?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          if (status) {
            return useById(id, statusNo);
          } else {
            return useById(id, statusNo);
          }
        }).then(() => {
          this.getList();
          this.msgSuccess(status + '成功')
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateApiServiceConfig(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.openTemplate = false;
                this.openChildTemplates = false;
                this.getList();
              });
            } else {
              addApiServiceConfig(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.openTemplate = false;
                this.openChildTemplates = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除API服务配置编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delApiServiceConfig(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('integration/apiServiceConfig/export', {
          ...this.queryParams
        }, `integration_apiServiceConfig.xlsx`)
      },
      /** 测试API操作 */
      handleApiTest(row) {
        this.reset();
        this.form = row;
        this.openTest = true;
        this.title = "API测试";
      },
      test() {
        let data = {"apiId": this.form.id, "param": this.form.paramTemplate};
        testApi(data).then(response => {
          this.responseResult = JSON.stringify(response);
          this.msgSuccess("测试成功");
        });
      },
      /** 打开模板编辑 */
      handleOpenTemplate(row){
        this.reset();
        const id = row.id
        getApiServiceConfig(id).then(response => {
          this.form = response.data;
          this.openTemplate = true;
          this.title = "更改API模板配置";
        });
      }
    }
  };
</script>
